<template>
  <div class="program-practice">
    <div class="problem-container">
      <div class="problem-description">
        <!-- 顶部导航栏 -->
        <div class="problem-header">
          <div class="header-left">
            <div class="menu-icon">
              <unordered-list-outlined />
            </div>
            <div class="tab-navigation">
              <div
                v-for="tab in tabs"
                :key="tab.key"
                :class="['tab-item', { active: activeTab === tab.key }]"
                @click="activeTab = tab.key"
              >
                {{ tab.label }}
                <span v-if="tab.count" class="tab-count">({{ tab.count }})</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 题目信息栏 -->
        <div class="problem-info-bar" v-if="activeTab === 'description'">
          <div class="info-left">
            <span class="difficulty-label">难度:</span>
            <a-tag
              v-for="(item, key) in parsedTags"
              :key="key"
              :color="getKnowledgePointColor(item)"
              class="difficulty-tag"
            >
              {{ item }}
            </a-tag>
            <span class="time-limit">单个测试用例时限: <strong>3秒</strong></span>
          </div>
        </div>

        <!-- Tab内容区域 -->
        <div class="problem-tabs-content">
          <div v-show="activeTab === 'description'" class="tab-content">
            <ProblemDescription :question-data="currentQuestion" />
          </div>
          <div v-show="activeTab === 'answer'" class="tab-content">
            <ProblemAnswer :question-data="currentQuestion" />
          </div>
          <div v-show="activeTab === 'comments'" class="tab-content">
            <ProblemComments :question-data="currentQuestion" />
          </div>
          <div v-show="activeTab === 'submissions'" class="tab-content">
            <ProblemSubmissions :question-submit-data="currentQuestionSubmitVO"
                                :question-data="currentQuestion"
            />
          </div>
        </div>
      </div>
      <div class="code-editor">
        <div class="editor-header">
          <div class="editor-title"><code-outlined /> 代码编辑器</div>
          <div class="editor-actions">
            <div class="theme-switch">
              <bulb-filled v-if="isDarkTheme" class="theme-icon" />
              <bulb-outlined v-else class="theme-icon" />
              <a-switch
                v-model:checked="isDarkTheme"
                @change="toggleEditorTheme"
                size="small"
                class="theme-toggle"
              />
            </div>
            <a-select
              v-model:value="selectedLanguage"
              style="width: 120px"
              class="language-select"
              @change="handleLanguageChange"
            >
              <a-select-option value="java">Java</a-select-option>
              <a-select-option value="javascript">JavaScript</a-select-option>
              <a-select-option value="python">Python</a-select-option>
              <a-select-option value="cpp">C++</a-select-option>
            </a-select>
          </div>
        </div>
        <div ref="editorContainer" class="monaco-editor"></div>
        <div class="action-bar">
          <a-button type="primary" @click="runCode" class="action-button run-button">
            <play-circle-outlined /> 运行代码
          </a-button>
          <a-button type="primary" @click="submitCode" class="action-button submit-button">
            <check-circle-outlined /> 提交代码
          </a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, reactive, computed } from 'vue'
import * as monaco from 'monaco-editor'
import { useRoute, useRouter } from 'vue-router'
import {
  CodeOutlined,
  PlayCircleOutlined,
  CheckCircleOutlined,
  BulbOutlined,
  BulbFilled,
  UnorderedListOutlined,
} from '@ant-design/icons-vue'
import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker'
// 导入tsWorker
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker'
import { message } from 'ant-design-vue'
import { usePracticeStore } from '@/store/practice'
import { doQuestionSubmit } from '@/api/questionSubmitController'
import { getQuestionById, getQuestionSubmitById } from '@/api/questionController'
// 导入tab组件
import ProblemDescription from '@/components/student/programtabs/ProblemDescription.vue'
import ProblemAnswer from '@/components/student/programtabs/ProblemAnswer.vue'
import ProblemComments from '@/components/student/programtabs/ProblemComments.vue'
import ProblemSubmissions from '@/components/student/programtabs/ProblemSubmissions.vue'
const editorContainer = ref<HTMLElement | null>(null)
let editor: monaco.editor.IStandaloneCodeEditor | null = null
const selectedLanguage = ref('java')

const currentQuestion = ref<API.Question>()
const route = useRoute()

// Tab相关状态
const activeTab = ref('description')

// Tab配置
const tabs = computed(() => [
  { key: 'description', label: '任务描述' },
  { key: 'answer', label: '题解', count: currentQuestion.value?.acceptedNum || 86 },
  { key: 'comments', label: '评论', count: 64 },
  { key: 'submissions', label: '提交记录' },
])

// 解析标签数据
const parsedTags = computed(() => {
  if (!currentQuestion.value?.tags) return []
  try {
    return JSON.parse(currentQuestion.value.tags)
  } catch (e) {
    console.error('解析标签失败:', e)
    return []
  }
})
/**
 * 得到当前题目
 */
const fetchData = async () => {
  const id = route.params.id
  try {
    const res = await getQuestionById({
      id: id,
    })
    if (res.data.data && res.data.code === 0) {
      currentQuestion.value = res.data.data
    } else {
      message.error('获取题目数据失败' + res.data.msg)
    }
  } catch (e) {
    message.error('获取题目数据失败')
  }
}
/**
 * 获取当前题目的提交历史
 */
const currentQuestionSubmitVO = ref<API.QuestionSubmitVO[]>([])
const fetchSubmitHistory = async () => {
  const id = route.params.id
  try {
    const res = await getQuestionSubmitById({
      questionId: id,
    })
    if (res.data.data && res.data.code === 0) {
      currentQuestionSubmitVO.value = res.data.data ?? []
      console.log(currentQuestionSubmitVO.value)
    } else {
      if(!(res.data.msg === "请求数据不存在")){
        message.error('获取题目提交数据失败' + res.data.msg)
      }
    }
  } catch (e) {
    console.log(e)
    message.error('获取题目提交数据失败')
  }
}
// 主题设置
const isDarkTheme = ref(true) // 默认使用暗色主题

// 切换编辑器主题
const toggleEditorTheme = (checked: boolean) => {
  if (!editor) return

  const theme = checked ? 'vs-dark' : 'vs'
  monaco.editor.setTheme(theme)

  // 更新编辑器相关元素样式
  const codeEditorEl = document.querySelector('.code-editor') as HTMLElement
  if (codeEditorEl) {
    codeEditorEl.style.backgroundColor = checked ? '#1e1e1e' : '#ffffff'
    codeEditorEl.style.color = checked ? '#e6e6e6' : '#333333'

    // 更新编辑器头部
    const editorHeaderEl = codeEditorEl.querySelector('.editor-header') as HTMLElement
    if (editorHeaderEl) {
      editorHeaderEl.style.backgroundColor = checked ? '#252526' : '#f5f5f5'
      editorHeaderEl.style.color = checked ? '#e6e6e6' : '#333333'
      editorHeaderEl.style.borderBottom = checked
        ? '1px solid rgba(255,255,255,0.1)'
        : '1px solid rgba(0,0,0,0.1)'
    }

    // 更新主题切换开关旁边的图标颜色
    const themeIconEls = document.querySelectorAll('.theme-icon')
    themeIconEls.forEach((icon: Element) => {
      ;(icon as HTMLElement).style.color = checked ? '#e6e6e6' : '#333333'
    })

    // 更新主题切换区域背景
    const themeSwitchEl = document.querySelector('.theme-switch') as HTMLElement
    if (themeSwitchEl) {
      themeSwitchEl.style.backgroundColor = checked ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.05)'
    }
  }
}

// 获取对应语言的默认代码
const getDefaultCodeForLanguage = (language: string): string => {
  switch (language) {
    case 'javascript':
      return `/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
function twoSum(nums, target) {
    // 请在这里编写你的代码

    return [];
}

// 测试用例
console.log(twoSum([2, 7, 11, 15], 9)); // 应输出 [0, 1]`
    case 'python':
      return `class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        # 请在这里编写你的代码

        return []

# 测试用例
solution = Solution()
print(solution.twoSum([2, 7, 11, 15], 9)) # 应输出 [0, 1]`
    case 'java':
      return `public class Main {
    public int[] twoSum(int[] nums, int target) {
        // 请在这里编写你的代码

        return new int[]{0, 0};
    }
    public static void main(String[] args) {
        int var1 = Integer.parseInt(args[0]);
        int var2 = Integer.parseInt(args[1]);
        System.out.println((var1 + var2));
    }
}`
    case 'cpp':
      return `#include <vector>
#include <iostream>
using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        // 请在这里编写你的代码

        return {0, 0};
    }
};

int main() {
    Solution solution;
    vector<int> nums = {2, 7, 11, 15};
    vector<int> result = solution.twoSum(nums, 9);
    cout << "[" << result[0] << ", " << result[1] << "]" << endl; // 应输出 [0, 1]
    return 0;
}`
    default:
      return '// 请在这里编写你的代码'
  }
}

// 处理语言切换
const handleLanguageChange = (newLanguage: string) => {
  if (editor) {
    // Monaco编辑器正常工作
    try {
      //1.切换语言模式
      const model = editor.getModel()
      if (model) {
        monaco.editor.setModelLanguage(model, newLanguage)
      }
      //2.获取新语言的示例代码
      const newDefaultCode = getDefaultCodeForLanguage(selectedLanguage.value).trim()
      //3.切换对应的示例代码
      editor.setValue(newDefaultCode)
    } catch (e) {
      message.error('切换语言失败')
    }
  }
}

// 监听语言变化
watch(selectedLanguage, handleLanguageChange)

//store
const practiceStore = usePracticeStore()

onMounted(() => {
  fetchData()
  fetchSubmitHistory()
  //work 的加载
  window.MonacoEnvironment = {
    getWorker(_workerId: any, label: string) {
      if (label === 'typescript' || label === 'javascript') {
        // 用tsWorker
        return new tsWorker()
      }
      return new editorWorker()
    },
  }
  // 从 store 获取题目信息 生成题目
  const questionData = practiceStore.getCurrentPractice()
  // 尝试初始化Monaco编辑器
  setTimeout(() => {
    try {
      const defaultCode = getDefaultCodeForLanguage(selectedLanguage.value)

      if (editorContainer.value && typeof monaco !== 'undefined') {
        // 使用最简单的配置
        editor = monaco.editor.create(editorContainer.value, {
          value: defaultCode,
          language: selectedLanguage.value,
          theme: isDarkTheme.value ? 'vs-dark' : 'vs',
          minimap: { enabled: true },
          automaticLayout: true,
        })
      } else {
        console.error('Monaco编辑器未加载或容器不存在')
        message.error('编辑器加载失败')
      }
    } catch (err) {
      console.error('Monaco编辑器初始化失败:', err)
      message.error('编辑器初始化失败')
    }
  }, 100) // 短暂延迟以确保DOM已完全加载
})

onBeforeUnmount(() => {
  if (editor) {
    editor.dispose()
  }
})

const submitCode = async () => {
  let code = ''
  if (editor) {
    // Monaco编辑器正常工作
    code = editor.getValue()
    //保存用户提交的代码
    // const questionData = practiceStore.getCurrentPractice()
    // questionData.userAns = code
    // practiceStore.setCurrentPractice(questionData)
    message.success('代码提交成功')
    const submitParam = reactive<API.QuestionSubmitAddRequest>({
      language: selectedLanguage.value,
      code: code,
      questionId: currentQuestion.value?.id,
    })
    console.log(submitParam)
    const res = await doQuestionSubmit({
      ...submitParam,
    })
    if (res.data.data && res.data.code === 0) {
      console.log(res.data.data)
    }
  } else {
    message.warning('编辑器未就绪，无法提交代码')
    return
  }
}

const runCode = () => {
  message.warn('运行代码功能维护中，敬请期待...')
}
// 知识点颜色映射（动态生成）
const knowledgePointColors = [
  'magenta',
  'red',
  'volcano',
  'orange',
  'gold',
  'lime',
  'green',
  'cyan',
  'blue',
  'geekblue',
  'purple',
  'pink',
]

const getKnowledgePointColor = (knowledgePoint: string) => {
  if (!knowledgePoint) return 'default'

  // 使用字符串哈希生成稳定的颜色索引
  let hash = 0
  for (let i = 0; i < knowledgePoint.length; i++) {
    const char = knowledgePoint.charCodeAt(i)
    hash = (hash << 5) - hash + char
    hash = hash & hash // 转换为32位整数
  }

  // 确保索引为正数并在颜色数组范围内
  const colorIndex = Math.abs(hash) % knowledgePointColors.length
  return knowledgePointColors[colorIndex]
}
</script>

<style scoped>
.program-practice {
  display: flex;
  flex-direction: column;
  height: 87vh;
  background-color: var(--background-color, #f5f5f5);
  position: relative;
  overflow: hidden;
}

/* 问题描述区域头部 */
.problem-header {
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
  flex-shrink: 0;
}

.header-left {
  display: flex;
  align-items: center;
  padding: 0;
}

.menu-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background: #4096ff;
  color: white;
  font-size: 14px;
  border-radius: 6px;
  margin: 8px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(64, 150, 255, 0.2);
}

.menu-icon:hover {
  background: #1677ff;
  box-shadow: 0 4px 8px rgba(64, 150, 255, 0.3);
  transform: translateY(-1px);
}

.tab-navigation {
  display: flex;
  align-items: center;
  gap: 0;
  flex: 1;
}

.tab-item {
  display: flex;
  align-items: center;
  padding: 14px 20px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  border-bottom: 3px solid transparent;
  transition: all 0.3s ease;
  white-space: nowrap;
  position: relative;
  background: transparent;
}

.tab-item:hover {
  color: #4096ff;
  background: rgba(64, 150, 255, 0.06);
}

.tab-item.active {
  color: #4096ff;
  border-bottom-color: #4096ff;
  font-weight: 600;
  background: rgba(64, 150, 255, 0.04);
}

.tab-count {
  margin-left: 4px;
  font-size: 12px;
  color: #999;
  font-weight: normal;
}

.problem-container {
  display: flex;
  flex: 1;
  gap: 20px;
  padding: 16px;
  overflow: hidden;
  height: 100%;
}

.problem-description {
  flex: 4; /* 调整为4份比例 */
  background-color: var(--card-background, #ffffff);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 0; /* 移除padding，由内部元素管理 */
  overflow: hidden; /* 改为hidden，由内部元素管理滚动 */
  transition: box-shadow 0.3s;
  display: flex;
  flex-direction: column;
}

/* 题目信息栏样式 */
.problem-info-bar {
  display: flex;
  align-items: center;
  padding: 10px 24px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  flex-shrink: 0;
  gap: 16px;
  font-size: 13px;
}

.info-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.difficulty-label {
  font-size: 13px;
  color: #666;
  font-weight: 500;
}

.difficulty-tag {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  font-weight: 500;
  margin-right: 4px;
}

.time-limit {
  font-size: 13px;
  color: #666;
  margin-left: 8px;
}

.time-limit strong {
  color: #333;
  font-weight: 600;
}

/* Tab内容区域样式 */
.problem-tabs-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.tab-content {
  height: 100%;
  overflow: hidden;
}

.problem-description:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.code-editor {
  flex: 6; /* 调整为6份比例 */
  display: flex;
  flex-direction: column;
  background-color: var(--editor-background, #1e1e1e);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: relative;
  transition: box-shadow 0.3s;
}

.code-editor:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: var(--editor-header-background, #252526);
  color: var(--editor-text-color, #e6e6e6);
}

.editor-title {
  font-size: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
}

.theme-switch {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-right: 15px;
  background-color: rgba(255, 255, 255, 0.05);
  padding: 4px 8px;
  border-radius: 20px;
  transition: all 0.3s;
}

.theme-switch:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.theme-icon {
  font-size: 16px;
  color: var(--editor-text-color, #e6e6e6);
  transition:
    color 0.3s,
    transform 0.3s;
}

.theme-icon:hover {
  transform: scale(1.2);
}

.theme-toggle :deep(.ant-switch) {
  background-color: rgba(0, 0, 0, 0.25);
  min-width: 32px;
  height: 16px;
}

.theme-toggle :deep(.ant-switch-handle) {
  height: 12px;
  width: 12px;
  top: 2px;
}

.theme-toggle :deep(.ant-switch-checked) {
  background-color: var(--primary-color, #1890ff);
}

.theme-toggle :deep(.ant-switch-checked:hover) {
  background-color: var(--primary-color, #40a9ff);
}

.editor-actions {
  display: flex;
  align-items: center;
}

.monaco-editor {
  flex: 1;
  width: 100%;
}

.action-bar {
  position: absolute;
  bottom: 20px;
  right: 20px;
  display: flex;
  gap: 16px;
  z-index: 10;
}

.action-button {
  border-radius: 20px;
  height: 40px;
  padding: 0 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transition: all 0.3s;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.run-button {
  background: linear-gradient(45deg, #52c41a, #1890ff);
  border: none;
}

.run-button:hover {
  background: linear-gradient(45deg, #73d13d, #40a9ff);
}

.submit-button {
  background: linear-gradient(45deg, #1890ff, #722ed1);
  border: none;
}

.submit-button:hover {
  background: linear-gradient(45deg, #40a9ff, #9254de);
}

/* 运行结果区域 */
.result-container {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: var(--card-background, #ffffff);
  border-radius: 12px 12px 0 0;
  box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.1);
  max-height: 50vh;
  z-index: 20;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.result-title {
  font-size: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--heading-color, #1f1f1f);
}

.result-content {
  padding: 20px;
  overflow-y: auto;
  max-height: calc(50vh - 60px);
}

.result-details {
  display: flex;
  justify-content: center;
  gap: 40px;
  margin: 20px 0;
}

.result-item {
  text-align: center;
}

.result-label {
  font-size: 14px;
  color: var(--text-color-secondary, #999);
  margin-bottom: 8px;
}

.result-value {
  font-size: 24px;
  font-weight: 600;
  color: var(--primary-color, #1890ff);
}

.output-code {
  background-color: var(--code-background, #f6f8fa);
  padding: 16px;
  border-radius: 8px;
  font-family: 'Courier New', Courier, monospace;
  white-space: pre-wrap;
  word-break: break-word;
  margin: 16px auto;
  max-width: 600px;
  border-left: 4px solid var(--primary-color, #1890ff);
  color: var(--code-text, #333);
  font-size: 14px;
  line-height: 1.6;
  overflow-x: auto;
}

.language-select :deep(.ant-select-selector) {
  background-color: rgba(255, 255, 255, 0.1) !important;
  border-color: rgba(255, 255, 255, 0.2) !important;
  color: #e6e6e6 !important;
}

.language-select :deep(.ant-select-selection-item) {
  color: #e6e6e6 !important;
}

.language-select :deep(.ant-select-arrow) {
  color: #e6e6e6 !important;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .problem-container {
    flex-direction: column;
  }

  .problem-description,
  .code-editor {
    width: 100%;
  }

  .result-container {
    max-height: 70vh;
  }
}
</style>
